using System;
using System.Drawing;
using FIRADriverLibrary;
using Geometry;

namespace PotentialFieldDriver
{
	/// <summary>
	/// ball only for now
	/// </summary>
	public abstract class Predicator
	{
		private const double ball_OnColisionVelocityAttenuation = 0.4;

		public static FIRADriver firaDriver;
		public static RectangleF pitchArea;

		private static Point2D prevBallPosition;
		private static double prevTime;

		private static double vx, vy;
      
		public static void Refresh()
		{
			if (prevTime == firaDriver.time)
				return;

			vx = vx * 5 + (firaDriver.ballX - prevBallPosition.x) / (firaDriver.time - prevTime);
			vx /= 6;
			vy = vy * 5 + (firaDriver.ballY - prevBallPosition.y) / (firaDriver.time - prevTime);
			vy /= 6;
			
			prevBallPosition.x = firaDriver.ballX;
			prevBallPosition.y = firaDriver.ballY;
			prevTime = firaDriver.time;
		}

		public static double VX
		{
			get { return vx; }
		}
		public static double VY
		{
			get { return vy; }
		}

		public static Vector2D V
		{
			get { return new Vector2D(vx, vy); }
		}


		public static Point2D GetBallPosition(double eta)
		{
			Point2D ballPosition = new Point2D(firaDriver.ballX, firaDriver.ballY);
			ballPosition.x += eta * vx;
			ballPosition.y += eta * vy;

			// walls collisions
			bool changed;
			do 
			{
				changed = false;
				if (ballPosition.x < pitchArea.Left)
				{
					ballPosition.x = pitchArea.Left + (pitchArea.Left - ballPosition.x) * ball_OnColisionVelocityAttenuation;
					changed = true;
				}
				if (ballPosition.x > pitchArea.Right)
				{
					ballPosition.x = pitchArea.Right - (ballPosition.x - pitchArea.Right) * ball_OnColisionVelocityAttenuation;
					changed = true;
				}

				if (ballPosition.y < pitchArea.Top)
				{
					ballPosition.y = pitchArea.Top + (pitchArea.Top - ballPosition.y) * ball_OnColisionVelocityAttenuation;
					changed = true;
				}
				if (ballPosition.y > pitchArea.Bottom)
				{
					ballPosition.y = pitchArea.Bottom - (ballPosition.y - pitchArea.Bottom) * ball_OnColisionVelocityAttenuation;
					changed = true;
				}

			}while (changed);   
         
			return ballPosition;
		}
	
	}
}
